package com.bw.controller;

import com.bw.domain.Role;
import com.bw.domain.TbMenu;
import com.bw.domain.User;
import com.bw.service.UserService;
import com.bw.utils.CheckUtil;
import com.bw.utils.R;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zhaijiaqi
 * @Date: 2025/3/12 15:17
 * @Description:
 **/
@Controller
@RequestMapping("auth")
public class AuthController {

    @Autowired
    UserService userService;

    @Autowired
    RedisTemplate redisTemplate;

    /**
     *去往登录页面
     * @return
     */
    @RequestMapping("tologin")
    public String tologin(){
        return "login";
    }

    Integer total=5;
    /**
     * 执行登录
     * @param username
     * @param password
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("login")
    public R login(String username, String password, HttpSession session){
        String filetime="filetime"+username;
        String filelock="filelock"+username;
        Object o = redisTemplate.opsForValue().get(filelock);
        if(o!=null){
            return R.ERROR(500,"账户锁定请五分钟后再试");
        }

        if(username.length()<8){
            return R.ERROR(500,"用户名不能小于八位");
        }
        if(password.length()<6){
            return R.ERROR(500,"密码不能小于六位");
        }
        if(!CheckUtil.mustNumAndLetter(password)){
            return R.ERROR(500,"密码必须包含字母和数字");
        }
        if(StringUtil.isEmpty(username)){
            return R.ERROR(500,"用户名不能为空");
        }
       User user= userService.getlogin(username);
        if(user==null){
            return R.ERROR(500,"用户不存在");
        }

        if(StringUtil.isEmpty(password)){
            return R.ERROR(500,"密码不能为空");
        }

        if(!user.getPassword().equals(password)){
            Long filetime1 = redisTemplate.opsForValue().increment(filetime, 1);
            if(filetime1>=total){
                redisTemplate.opsForValue().set(filelock,1,5, TimeUnit.MINUTES);
            }

            return R.ERROR(500,"密码错误还可以尝试"+(total-filetime1)+"次");

        }

        User user1= userService.getuser(user.getId());
        redisTemplate.opsForValue().set("user1",user1);

       List<Role> roleList= userService.getrolelist(user.getId());
        redisTemplate.opsForValue().set("roleList"+user.getId(),roleList);

       List<TbMenu> tbMenuList= userService.getmenulist(user.getId());
       redisTemplate.opsForValue().set("tbMenuList"+user.getId(),tbMenuList);

        session.setAttribute("user",user);



        return R.OK();
    }


}
